import {
    login,
    listTenant,
    getInfo
} from '@/api/login';
import store from '@/store';

export default {
    // 全局配置
    config: require('@/config.js'),
    // 自动登录
    async autoLogin() {
        const userInfo = uni.getStorageSync('userInfo');
        if (!userInfo) {
            try {
                await this.login();
            } catch (error) {
                console.error("自动登录失败", error);
            }
        } else {
            console.log("用户已经登录");
        }
    },

    // 登录方法
    async login() {
        try {
            const [loginErr, loginRes] = await uni.login({});
            if (loginErr) {
                return;
            }
            const code = loginRes.code;
            const tenantListRes = await this.listTenant();
            if (tenantListRes.code !== 200 || !tenantListRes.data || tenantListRes.data.voList.length === 0) {
                return;
            }
            const tenantId = tenantListRes.data.voList[0].tenantId;
            const sharePid = uni.getStorageSync('sharePid');
            const loginForm = {
                tenantId: tenantId,
                clientId: this.config.clientId,
                grantType: this.config.grantType,
                appid: this.config.appId,
                xcxCode: code,
                sharePid: sharePid 
            };
            await store.dispatch('Login', loginForm);
            await store.dispatch('GetInfo');
        } catch (error) {
            throw error;
        }
    },

    async listTenant() {
        try {
            const res = await listTenant();
            if (res.code === 200) {
                return res;
            } else {
                return {
                    code: 500,
                    data: null
                };
            }
        } catch (error) {
            return {
                code: 500,
                data: null
            };
        }
    },

    async checkLoginAndNavigate(targetUrl) {
        const token = store.state.user.token;
        if (!token) {
            uni.showToast({
                title: '请先登录！',
                icon: 'none'
            });
        } else {
            uni.navigateTo({
                url: targetUrl,
            });
        }
    },
};